package com.juku2024.juku.tools;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

public class ChannelUtil {

    private static String KEY_CHANNEL = "CHANNEL_VALUE";

    public static String getChannel(Context context){
        return getMetaValue(context, KEY_CHANNEL);
    }
    /**
     * 获取 MetaValue
     * @param context 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
    public static String getMetaValue(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return null;
        }

        Log.e("Unity", "context type: " + context.getClass().getName());
        String channelName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo =
                        packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null && applicationInfo.metaData != null) {
                    Object obj = applicationInfo.metaData.get(key);
                    if (obj != null) {
                        return  obj.toString();
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }
}
